package com.probiz.estore.order.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.order.OrderShipment;
import com.probiz.estore.common.model.system.ShippingMethod;
import com.probiz.estore.core.service.impl.GenericManagerImpl;
import com.probiz.estore.order.dao.OrderShipmentDao;
import com.probiz.estore.order.service.OrderShipmentManager;
import com.probiz.estore.system.dao.ShippingMethodDao;


/**
 * Manager implementation for OrderShipment, responsible for business processing, and communicate between web and persistence layer.
 */
public class OrderShipmentManagerImpl extends GenericManagerImpl<OrderShipment> implements OrderShipmentManager {

	private OrderShipmentDao orderShipmentDao ;
	private ShippingMethodDao shippingMethodDao ;

	/**
	 * @param orderShipmentDao
	 *            the orderShipmentDao to set
	 */
	public void setOrderShipmentDao(OrderShipmentDao orderShipmentDao) {
		this.orderShipmentDao = orderShipmentDao;
	}
	

	public void setShippingMethodDao(ShippingMethodDao shippingMethodDao) {
		this.shippingMethodDao = shippingMethodDao;
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#init()
	 */
	@Override
	protected void initManager() {
		dao = orderShipmentDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preDelete(java.lang.Object)
	 */
	@Override
	protected void preDelete(OrderShipment entity) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preSave(java.lang.Object)
	 */
	@Override
	protected void preSave(OrderShipment entity) {

	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.order.service.OrderShipmentManager#getByDocumentNo(java.lang.String)
	 */
	public OrderShipment getByDocumentNo(String documentNo){
		return (OrderShipment)orderShipmentDao.findUnique("from OrderShipment oi where oi.documentNo = ?", documentNo);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.order.service.OrderShipmentManager#getSizeByDocumentNo(java.lang.String)
	 */
	public Long getSizeByDocumentNo(String documentNo){
		return orderShipmentDao.countByHql("from OrderShipment o where o.documentNo = ?", documentNo);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.order.service.OrderShipmentManager#queryKuaidi100(java.lang.String)
	 */
	public Short queryKuaidi100(String documentNo){
		Short flag = (short)0;//默认查询没有结果
		OrderShipment orderShipment = this.getByDocumentNo(documentNo);
		orderShipment.setKuaidi100QueryTime(new Date());
		orderShipment.setKuaidi100Message(null);
		if(StringUtils.isBlank(orderShipment.getTrackingNo())){
			//未填写物流跟踪号
			flag = (short)2;
		}else if(StringUtils.isNotBlank(orderShipment.getTrackingNo()) && (null !=orderShipment.getShippingMethodId())){
			ShippingMethod shippingMethod = shippingMethodDao.getById(orderShipment.getShippingMethodId());
			if(null != shippingMethod){
				if(StringUtils.isBlank(shippingMethod.getCarrier().getCarrierCode())){
					//物流公司没填写对应的公司代码
					flag = (short)3;
				}else{
					if(ConfigUtil.getInstance().getKuaidi100Type().equals(Constants.KUAIDI100_TYPE_1)){
						String message = getKuaidi100Context4LatestOne(orderShipment.getTrackingNo(),shippingMethod.getCarrier().getCarrierCode());
						orderShipment.setKuaidi100Message(message);
						flag = (short)1; //查询成功
					}else if(ConfigUtil.getInstance().getKuaidi100Type().equals(Constants.KUAIDI100_TYPE_2)){
						if(StringUtils.isNotBlank(ConfigUtil.getInstance().getKuaidi100IdKey())){
							String message = getKuaidi100Context4All(orderShipment.getTrackingNo(),shippingMethod.getCarrier().getCarrierCode(),ConfigUtil.getInstance().getKuaidi100IdKey());
							orderShipment.setKuaidi100Message(message);
							flag = (short)1; //查询成功
						}else{
							//没填写IdKey
							flag = (short)4;
						}
					}
				}
			}
		}
		orderShipmentDao.save(orderShipment);
		return flag;
		
	}
	/**
	 * 获取最近一条的物流信息 返回json字符串
	 * @return
	 */
	private String getKuaidi100Context4LatestOne(String trackingNo,String carrierCode){
		try {
			StringBuffer buffer = new StringBuffer();
			buffer.append("http://api.kuaidi100.com/apione?com=").append(carrierCode).append("&nu=").append(trackingNo);
			URL url = new URL(buffer.toString());
			URLConnection con = url.openConnection();
			con.setAllowUserInteraction(false);
			InputStream urlStream = url.openStream();
			String type = con.guessContentTypeFromStream(urlStream);
			String charSet = null;
			if (type == null)type = con.getContentType();
			if (type == null || type.trim().length() == 0|| type.trim().indexOf("text/html") < 0)return null;
			if (type.indexOf("charset=") > 0)charSet = type.substring(type.indexOf("charset=") + 8);

			byte b[] = new byte[10000];
			int numRead = urlStream.read(b);
			String content = new String(b, 0, numRead, charSet);
//			String content = new String(b, 0, numRead);
			while (numRead != -1) {
				numRead = urlStream.read(b);
				if (numRead != -1) {
//				    String newContent = new String(b, 0, numRead);	
					String newContent = new String(b, 0, numRead, charSet);
					content += newContent;
				}
			}
//			System.out.println("content:" + content);
			urlStream.close();
			return content;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取完整的物流信息 返回json字符串
	 * @return
	 */
	private String getKuaidi100Context4All(String trackingNo,String carrierCode,String idKey){
		try {
			StringBuffer buffer = new StringBuffer();
			buffer.append("http://api.kuaidi100.com/api?com=").append(carrierCode).append("&nu=").append(trackingNo);
			buffer.append("&id=").append(idKey).append("&muti=1&order=asc");
			URL url = new URL(buffer.toString());
			URLConnection con = url.openConnection();
			con.setAllowUserInteraction(false);
			InputStream urlStream = url.openStream();
			String type = con.guessContentTypeFromStream(urlStream);
			String charSet = null;
			if (type == null)type = con.getContentType();
			if (type == null || type.trim().length() == 0|| type.trim().indexOf("text/html") < 0)return null;
			if (type.indexOf("charset=") > 0)charSet = type.substring(type.indexOf("charset=") + 8);

			byte b[] = new byte[10000];
			int numRead = urlStream.read(b);
			String content = new String(b, 0, numRead, charSet);
			while (numRead != -1) {
				numRead = urlStream.read(b);
				if (numRead != -1) {
					String newContent = new String(b, 0, numRead, charSet);
					content += newContent;
				}
			}
			urlStream.close();
			return content;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


}
